<template>
  <ModalCard action @close="emits('close')" @submit="submit">
    <div style="padding: 43rem 36rem 20rem">
      <NSpin :show="spinShow">
        <div class="scope-box">
          <div style="margin-bottom: 10rem; display: flex">
            <div style="flex: 0 0 50%;display: flex;align-items: center;">
              <span style="width: auto;margin-right: 20px;">人员</span>
              <n-input v-model:value="pattern" placeholder="输入关键字搜索" style="width: 50%;" />
            </div>
            <div style="flex: 0 0 50%;display: flex;align-items: center;">
              <span>已选范围 (双击取消) ({{ seleteTransfer?.length || 0 }})</span>
              <NIcon size="24" style="cursor: pointer;margin: 0 5px;" @click="up">
                <ArrowUpwardSharp />
              </NIcon>
              <NIcon size="24" style="cursor: pointer" @click="low">
                <ArrowDownwardOutlined />
              </NIcon>
            </div>
          </div>
          <!-- 树形 -->
          <div style="margin-bottom: 10rem; display: flex">
            <div class="tree-box">
              <NScrollbar>
                <NTree style="height: 400rem;" ref="transfer" :data="options" checkable
                  v-model:checked-keys="seleteTransfer" cascade checkStrategy="child" expand-on-click block-line
                  :on-update-checked-keys="handleCheckedKeys" :checkOnClick="false" :selectable="false" keyField="value"
                  :defaultCheckedKeys="defaultCheckedKeys" :pattern="pattern" />
              </NScrollbar>
            </div>
            <div class="tree-box" id="selectRef">
              <NScrollbar>
                <template v-if="seleteTransfer?.length">
                  <div v-for="(item, index) in selectList" :key="index">
                    <div v-if="seleteTransfer.includes(item.identifyingId)" class="selete-box"
                      @dblclick="handleDblClick(item.identifyingId)" @click="clickInd(index)"
                      :style="{ backgroundColor: clickIndex == index ? '#5fb17f' : 'transparent' }">
                      <div style="display: flex; margin-left: 15rem; flex: 0 0 40%">{{ item.typeName }}</div>
                    </div>
                  </div>
                </template>
              </NScrollbar>
            </div>
          </div>
          <!-- 单选 -->
          <n-radio-group v-model:value="seleteRadio" name="radiogroup">
            <n-radio v-for="item in radioList" :key="item.value" :value="item.value">
              {{ item.label }}
            </n-radio>
          </n-radio-group>
        </div>
      </NSpin>
    </div>
  </ModalCard>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useMessage, NTree, NRadio, NRadioGroup, NSpin, NInput, NScrollbar, NIcon } from 'naive-ui'
import ModalCard from '@/components/ModalCard.vue'
import { sendRequest } from '@/utils/api'
import { ArrowUpwardSharp, ArrowDownwardOutlined } from '@vicons/material'

const message = useMessage()
const pattern = ref() // 关键字
const emits = defineEmits(['close', 'scopeSubmit'])
const props = defineProps({
  defaultList: { type: Array, default: () => [] }, //默认选择数据
  otherDefaultList: { type: Array, default: () => [] }  //其他数据默认选择数据
})
const seleteTransfer: any = ref([]) //树形选择
const defaultCheckedKeys = props.defaultList?.length ? [...props.defaultList.map((it: any) => it.fullId)] : seleteTransfer.value
const OtherDefaultCheckedKeys = props.otherDefaultList?.length ? [...props.otherDefaultList.map((it: any) => it.fullId)] : []
const seleteRadio = ref('ULA0102') //单选框选择
const radioList = ref([{ label: '人员', value: 'ULA0102' }])

// 单机选择右侧数据
const clickIndex = ref()
const clickInd = (index: any) => clickIndex.value = index
// 上移
const up = () => {
  if (!clickIndex.value) return
  selectList.value.splice(clickIndex.value, 1, ...selectList.value.splice(clickIndex.value - 1, 1, selectList.value[clickIndex.value]))
  seleteTransfer.value.splice(clickIndex.value, 1, ...seleteTransfer.value.splice(clickIndex.value - 1, 1, seleteTransfer.value[clickIndex.value]))
  clickIndex.value = clickIndex.value - 1
}
// 下移
const low = () => {
  if (clickIndex.value == null || clickIndex.value == selectList.value?.length - 1) return
  selectList.value.splice(clickIndex.value, 1, ...selectList.value.splice(clickIndex.value + 1, 1, selectList.value[clickIndex.value]))
  seleteTransfer.value.splice(clickIndex.value, 1, ...seleteTransfer.value.splice(clickIndex.value + 1, 1, seleteTransfer.value[clickIndex.value]))
  clickIndex.value = clickIndex.value + 1
}
// 处理data数据
const identifyingIdList: any = ref([]) //公益性人员、员工的identifyingId数组
function createData(data: any) {
  if (!data?.length) return undefined
  return data.map((item: any) => {
    let flag = false
    const itemSonList = handeDataDisabled(item)
    const sonResultList: any = []
    itemSonList.forEach((c: any) => {
      const sonIndex = OtherDefaultCheckedKeys.findIndex((i: any) => i == c.identifyingId)
      sonIndex != -1 ? sonResultList.push(true) : sonResultList.push(false)
    })
    const result = sonResultList.some((c: any) => c)
    if (item.children?.length) OtherDefaultCheckedKeys?.length < sonResultList?.length ? flag = false : flag = result ? true : false
    else flag = OtherDefaultCheckedKeys.includes(item.identifyingId) ? true : false
    // 员工和公益性人员不能选择
    if (item.typeName == '员工' || item.typeName == '公益性人员') identifyingIdList.value.push(item.identifyingId), flag = true
    if (identifyingIdList.value.includes(item.parentId)) flag = true
    return {
      disabled: flag,
      label: item.typeName,
      value: item.identifyingId,
      children: createData(item.children)
    }
  })
}
// @ts-ignore 判断data数据是否禁用
const handeDataDisabled = (data: any) => {
  const tmp: any = []
  if (data.typeName == '员工' || data.typeName == '公益性人员') return []
  else if (data.children?.length) data.children.map((it: any) => tmp.push(...handeDataDisabled(it)))
  else tmp.push(data)
  return tmp
}
// 处理树形结构
const options: any = ref(undefined)
const flattenTree = (list: any) => {
  const result: any = []
  const flatten = (_list: any = []) => _list.forEach((item: any) => (result.push(item), flatten(item.children)))
  flatten(list)
  return result
}
// 获取数据
const spinShow = ref(false)
const allScope: any = ref([])
const getScopeList = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'scope',
    api: 'scopeOrPeople',
    override: {
      params: {
        code: seleteRadio.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  options.value = createData(res.data['ry'])
  if (!allScope.value.length) allScope.value.push(...flattenTree(res.data['ry']))
  spinShow.value = false
}
// tree选择
const handleCheckedKeys = (v: any) => {
  seleteTransfer.value = v
  handleRightList()
}
// 双击取消选择
const handleDblClick = (id: any) => {
  const index = seleteTransfer.value.findIndex((it: any) => it == id)
  if (index !== -1) seleteTransfer.value.splice(index, 1)
}
// 获取右侧循环数据
const selectList: any = ref([])
const handleRightList = () => {
  const tmp: any = []
  seleteTransfer.value.map((it: any) => {
    const T = allScope.value.find((c: any) => c.identifyingId == it)
    tmp.push(T)
  })
  selectList.value = tmp
}
// 确定
const submit = async () => {
  if (!seleteTransfer.value?.length) return message.error('暂无选择数据')
  const result = seleteTransfer.value.map((it: any) => {
    const tmp = allScope.value?.find((c: any) => c?.identifyingId == it)
    delete tmp?.children
    return tmp
  })
  result.map((it: any) => {
    it.fullId = it.identifyingId
    it.identifyingId = it.identifyingId?.split('-')[it.identifyingId?.split('-').length - 1]
  })
  emits('scopeSubmit', result)
}

onMounted(async () => {
  await getScopeList()
  if (props.defaultList?.length) {
    seleteTransfer.value = [...props.defaultList.map((it: any) => it.fullId)]
    handleRightList()
  }
})
</script>

<style scoped lang="css">
.scope-box {
  display: flex;
  flex-direction: column;
  background-color: #ebeceb;
  padding: 20rem;
  width: 900rem;
  height: 720rem;
  box-sizing: border-box;
}

.tree-box {
  flex: 0 0 50%;
  background-color: #fff;
  height: 600rem;
  border-right: 1rem solid #ccc;
  overflow-y: scroll;
}

.zhTitle {
  display: flex;
  align-items: center;
  width: 100%;
  height: 40rem;
  cursor: pointer;
  border-radius: 4rem;
  padding: 10rem;
}

.zhTitle:hover {
  animation: show 0.5s forwards;
}

.selete-box {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding: 10rem 0;
  align-items: center;
  border-radius: 4rem;
}

.selete-box:hover {
  animation: show 0.5s forwards;
}

@keyframes show {
  to {
    background-color: #e7f3ec;
  }
}

@keyframes hide {
  from {
    background-color: #e7f3ec;
  }

  to {
    background-color: transparent;
  }
}

.tree-box::-webkit-scrollbar {
  display: none;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-tree) {
  min-height: 400rem;
  height: auto !important;
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
}
</style>
